//
//  DepositChargeViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/9/27.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "DepositChargeViewController.h"
#import "AliPayServer.h"

@interface DepositChargeViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *amount1;
@property (weak, nonatomic) IBOutlet UIButton *amount2;
@property (weak, nonatomic) IBOutlet UIButton *amount3;
@property (weak, nonatomic) IBOutlet UIButton *amount4;
@property (weak, nonatomic) IBOutlet UIButton *amount5;
@property (weak, nonatomic) IBOutlet UIButton *otherAmount;
@property (weak, nonatomic) IBOutlet UIButton *wechatCharge;
@property (weak, nonatomic) IBOutlet UIButton *alipayCharge;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *amountBtnArr;

@property (strong, nonatomic) NSString *selectedAmount;
@property (strong, nonatomic) NSArray *amountArr;

@end

@implementation DepositChargeViewController

- (void)viewWillAppear:(BOOL)animated
{
	self.selectedAmount = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
	
	[self createUI];
}

- (void)createUI {
	self.navigationItem.title = @"面试服务费充值";
	NSInteger i = 0;
	for (UIButton *btn in self.amountBtnArr)
	{
		btn.layer.borderWidth = 1;
		btn.layer.borderColor = [kGrayColor CGColor];
		[btn setTitleColor:UIMainColorRGB forState:UIControlStateSelected];
		[btn addTarget:self action:@selector(selectAmountBtn:) forControlEvents:UIControlEventTouchUpInside];
		btn.tag = i++;
	}
	_amountArr = @[@"1000",@"2000",@"3000",@"4000",@"5000",@"0"];
	self.wechatCharge.tag = 11;
	self.alipayCharge.tag = 12;
	[self.wechatCharge addTarget:self action:@selector(chargeClick:) forControlEvents:UIControlEventTouchUpInside];
	[self.alipayCharge addTarget:self action:@selector(chargeClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)selectAmountBtn:(UIButton *)sender {
	for (UIButton *btn in self.amountBtnArr)
	{
		[btn setSelected:NO];
		btn.layer.borderColor = [kGrayColor CGColor];
	}
	sender.selected = YES;
	sender.layer.borderColor = [UIMainColorRGB CGColor];
	self.selectedAmount = self.amountArr[sender.tag];
	NSLog(@"selected amount is %@", self.selectedAmount);
}

- (void)chargeClick:(UIButton *)sender {
	
	if ([self.selectedAmount isEqualToString:@""]) {
		[self presentViewController:[LZCTools alertMessage:@"请选择充值金额"] animated:YES completion:nil];
		return;
	}
	
	if ([self.selectedAmount isEqualToString:@"0"]) {
		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请输入充值金额" preferredStyle:UIAlertControllerStyleAlert];
		//增加取消按钮；
		[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			
		}]];
		//增加确定按钮；
		[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			
			//获取第1个输入框；
			UITextField *amountTextField = alertController.textFields.firstObject;
			self.selectedAmount = amountTextField.text;
			NSLog(@"输入金额 = %@",amountTextField.text);
			NSString *channel;
			if (sender.tag == 11) {
				channel = @"wx_app";
			}
			else
				channel = @"ali_app";
			
			NSDictionary *param = @{@"type":@"bond",
									@"channel":channel,
									@"amount":[NSString stringWithFormat:@"%ld", (NSInteger)([self.selectedAmount doubleValue]*100)]
									};
			
			[[NetworkTool sharedTool] requestWithName:@"发起求职金充值" URLString:APIPaymentCharge parameters:param method:@"POST" callBack:^(id responseObject) {
				if ([channel isEqualToString:@"wx_app"]) {
					[AliPayServer wxPay:responseObject[@"data"][@"param_obj"]];
				}
				else if ([channel isEqualToString:@"ali_app"]) {
					
					[AliPayServer aliPay:responseObject[@"data"][@"param_str"] memo:@"充值成功"];
				}
			}];
			//若用户中途取消了，让他重新填写金额
			self.selectedAmount = @"0";
		}]];

		//定义第一个输入框；
		[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
			
			textField.placeholder = @"请输入充值金额";
			textField.keyboardType = UIKeyboardTypeDecimalPad;
			textField.delegate = self;
			
		}];
		[self presentViewController:alertController animated:true completion:nil];
	}
	else
	{
		NSString *channel;
		if (sender.tag == 11) {
			channel = @"wx_app";
		}
		else
			channel = @"ali_app";
		
		NSDictionary *param = @{@"type":@"bond",
								@"channel":channel,
								@"amount":[NSString stringWithFormat:@"%ld", [self.selectedAmount integerValue]*100]};
		
		[[NetworkTool sharedTool] requestWithName:@"发起求职金充值" URLString:APIPaymentCharge parameters:param method:@"POST" callBack:^(id responseObject) {
			if ([channel isEqualToString:@"wx_app"]) {
				[AliPayServer wxPay:responseObject[@"data"][@"param_obj"]];
			}
			else if ([channel isEqualToString:@"ali_app"]) {
				
				[AliPayServer aliPay:responseObject[@"data"][@"param_str"] memo:@"充值成功"];
			}
		}];
	}
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
	//限制只能输入数字
	BOOL isHaveDian = YES;
	if ([string isEqualToString:@" "]) {
		return NO;
	}
	
	if ([textField.text rangeOfString:@"."].location == NSNotFound) {
		isHaveDian = NO;
	}
	if ([string length] > 0) {
		
		unichar single = [string characterAtIndex:0];//当前输入的字符
		if ((single >= '0' && single <= '9') || single == '.') {
			//数据格式正确
			if([textField.text length] == 0){
				if(single == '.') {
					//[MBProgressHUD showError:@"请输入正确的价格"];
					[textField.text stringByReplacingCharactersInRange:range withString:@""];
					return NO;
				}
			}
			
			//输入的字符是否是小数点
			if (single == '.') {
				if(!isHaveDian) {
					//text中还没有小数点
					isHaveDian = YES;
					return YES;
					
				}else{
					//[MBProgressHUD showError:@"请输入正确的价格"];
					[textField.text stringByReplacingCharactersInRange:range withString:@""];
					return NO;
				}
			}else{
				//存在小数点
				if (isHaveDian) {
					
					//判断小数点的位数
					NSRange ran = [textField.text rangeOfString:@"."];
					if (range.location - ran.location <= 2) {
						return YES;
					}else{
						//[MBProgressHUD showError:@"请输入正确的价格"];
						return NO;
					}
				}else{
					return YES;
				}
			}
		}else{
			//输入的数据格式不正确
			//[MBProgressHUD showError:@"请输入正确的价格"];
			[textField.text stringByReplacingCharactersInRange:range withString:@""];
			return NO;
		}
	}
	else
	{
		return YES;
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
